package live.jialing.sip.message.box.service;

import live.jialing.sip.message.box.domain.InBox;
import live.jialing.sip.message.box.domain.Information;
import live.jialing.sip.message.box.domain.OutBoxEmployee;
import live.jialing.sip.message.box.dto.MessageDTO;
import live.jialing.sip.message.box.repository.InBoxRepository;
import live.jialing.sip.message.box.repository.InfomationRepository;
import live.jialing.sip.message.box.repository.OutBoxEmployeeRepository;
import live.jialing.sip.message.box.util.ReceiverUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by bzt on 2017/6/19.
 */
@Service
@Slf4j
public class MessageService {

    @Resource
    private InfomationRepository infomationRepository;

    @Resource
    private OutBoxEmployeeRepository outBoxEmployeeRepository;

    @Resource
    private InBoxRepository inBoxRepository;

    @Resource
    private ReceiverService receiverService;

    /**
     * 发送公司内部消息
     *
     * @param message
     */
    public void sendEmployeeMessage(MessageDTO message) {

        if (message == null) {
            log.warn("消息内容为空");
            return;
        }

        // 消息内容
        Information information = new Information();
        information.setContent(message.getContent());
        information.setTitle(message.getTitle());
        final Information information2 = infomationRepository.saveAndFlush(null,information);
        // 发件
        OutBoxEmployee outBoxEmployee = new OutBoxEmployee();
        outBoxEmployee.setInformation(information2);
        outBoxEmployee.setSender(message.getSender());
        outBoxEmployee.setReceiver(ReceiverUtil.serialization(message.getReceiver()));
        outBoxEmployee.setInformation(information);
        outBoxEmployeeRepository.saveAndFlush(null,outBoxEmployee);
        // 收件
        List<Long> userIds = receiverService.getReceiverUsers(message.getReceiver());
        List<InBox> inBoxes = userIds.stream().map(uid -> {
            InBox inBox = new InBox();
            inBox.setInformation(information2);
            inBox.setSender(message.getSender());
            inBox.setReceiver(uid);
            return inBox;
        }).collect(Collectors.toList());
        inBoxRepository.saveAndFlush(null,inBoxes);
    }

}
